package validation;

import utility.cardHelper;
import card.*;

/**
 * Card Combination - Pair-chain
 * Valid:	33-44-55, 66-77-88-99-1010-JJ
 * Invalid:	33-44, KK-AA-22
 * 
 */
public class PairChain extends Type{
	
	private static PairChain instance;
	
	/**
	 *  Private Constructor
	 *  Set instance to null(default)
	 */
	private PairChain(){
		super();
		instance = null;
	}
	
	/**
	 * Implementation of Singleton
	 * @return Type instance
	 */
	public static Type getInstance(){
		if(instance == null){
			instance = new PairChain();
		}
		return instance;
	}
	
	@Override
	public void clear(){
		instance = null;
	}
	
	@Override
	public int getPriority(Cardset thisHand){
		// TODO Auto-generated method stub
		int maxCardPriority = 0;
		int[] histogram = new int[16];
        for(int i=0;i<histogram.length;i++){
        	histogram[i] = 0;
        }
        for(int i=0;i<thisHand.count();i++){
        	histogram[cardHelper.value2priority(thisHand.getCard(i).getValue())]++;
        }
    	for(int i=0;i<histogram.length;i++){
    		if(histogram[i] == 2){
    			maxCardPriority = i;
    		} 
    	}
		return maxCardPriority;
	}

	@Override
	public Type identify(Cardset thisHand) {
		// TODO Auto-generated method stub
		int cardChain = 0;
		int maxCardPriority = -1;
		boolean isValid = false;
		int n = thisHand.count();
		if((lastHand == null && n >= 6 && n%2 == 0) || (lastHand != null && lastHand.count() == n)){
			isValid = true;
			int[] histogram = new int[16];
	        for(int i=0;i<histogram.length;i++){
	        	histogram[i] = 0;
	        }
	        for(int i=0;i<n;i++){
	        	histogram[cardHelper.value2priority(thisHand.getCard(i).getValue())]++;
	        }
        	for(int i=0;i<histogram.length;i++){
        		if(histogram[i] == 2){
        			// Max Card in Chain is A
        			if(i > cardHelper.value2priority('A')){
        				maxCardPriority = -1;
        				isValid = false;
        				break;
        			} else {
        				maxCardPriority = i;
        			}
        		} 
        	}
        	while(maxCardPriority >= 0){
        		if(histogram[maxCardPriority--] == 2){
        			cardChain++;
        		} else if(cardChain != n/2){
        			isValid = false;
        			break;
        		}
        	}
 
		}
		
		if(isValid)
			return getInstance();
		else
			return null;
	}

}
